#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ==================================================
# @File    : runApi
# @IDE     : PyCharm
# @Author  : liuxiangui
# @Date    : 2023/12/30 10:47
# @Describe: 运行API
# ==================================================
import re

import allure
from requests import Response
from jsonpath import jsonpath
from typing import Dict, List, Tuple
from library.log import logger
from library.base.baseapi import BaseAPI
from library.assertion.assert_driver import AssertDriver
from library.base.mysqldriver import MysqlDriver


def run_api_return_response(api,
                            headers: Dict = {},
                            data: Dict = {},
                            is_json: bool = True
                            ) -> Response:
    """
    运行api，返回Response类型
    :param api: api
    :param headers: headers
    :param data: data
    :param is_json: bool
    :return: Response
    """
    api_object = api()  # type:BaseAPI
    api_object.headers.update(headers)
    api_object.data.update(data)
    api_object.isJson = is_json
    response = api_object.run()  # type: Response
    del api_object
    return response


def auto_run_api(api):
    ...


def run_api_return_json_or_text(api,
                                headers: Dict = {},
                                data: Dict = {},
                                checkpoint: List = [],
                                is_json: bool = True
                                ):
    """
    运行api，返回json/text
    :param api: api
    :param headers: 新请求头
    :param data: 新请求体
    :param checkpoint:  检查点列表；示例：[("code", "==", 200), ("$..key", "contains", "花果山"), (len("$..key"), ">", 200)]
    :param is_json: bool
    :return: Dict，Text
    """
    api_object = api()  # type:BaseAPI
    api_object.headers.update(headers)
    api_object.data.update(data)
    api_object.isJson = is_json
    response = api_object.run()  # type: Response
    # 判断响应内容的类型
    content_type = response.headers["Content-Type"]
    response.encoding = response.apparent_encoding
    if "json" in content_type:
        response_json = response.json()
        logger.info(response_json, attach_name="响应体")
        if checkpoint:
            assert_json(response_json, checkpoint)
        return response_json
    elif "text" in content_type or "html" in content_type or "plain" in content_type:
        response_text = response.text
        logger.info(response_text, attach_name="响应体")
        return response_text


def assert_json(response, checkpoint: List[Tuple]):
    """
    通过jsonpath语法，获取数据，并进行断言
    :param response: 被断言json
    :param checkpoint: 检查点
    :return: None
    """
    for point in checkpoint:
        logger.info(f"{point[0]} {point[1]} {point[2]}", attach_name="检查点")
        check_value_json_path = re.findall("len\((.*?)\)", point[0])[0] if "len(" in point[0] else point[0]
        check_value = len(jsonpath(response, check_value_json_path)[0])
        assert_type = point[1]
        expect_value = point[2]
        AssertDriver.assert_driver(check_value, assert_type, expect_value, "Assert Error !!!")
def assert_text(response, checkpoint: List[Tuple]):
    for point in checkpoint:
        logger.info(f"{point[0]} {point[1]} {point[2]}", attach_name="检查点")
        check_value = response.text

@allure.step("sql查询")
def query_database_sql(query_sql):
    db_obj = MysqlDriver()
    data = db_obj.query(query_sql, is_to_dict=False)
    print(data)

